#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_007.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_007.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test7.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <nettle/yarrow.h>
#include <fcntl.h>
#include <unistd.h>

#define RANDOM_BUFFER_SIZE 16
#define NUM_RANDOM_CHUNKS 10

/* 简易函数，从 /dev/urandom 读取熵数据 */
void read_entropy_from_dev_urandom(struct yarrow256_ctx *ctx, size_t length) {
    int fd = open("/dev/urandom", O_RDONLY);
    if (fd < 0) {
        perror("打开 /dev/urandom 是失败");
        exit(EXIT_FAILURE);
    }
    
    uint8_t entropy[length];
    ssize_t result = read(fd, entropy, length);
    if (result < 0 || (size_t)result != length) {
        perror("读取熵数据失败");
        close(fd);
        exit(EXIT_FAILURE);
    }
    
    yarrow256_seed(ctx, length, entropy);
    
    close(fd);
}

int main() {
    struct yarrow256_ctx rng;
    
    // 初始化 Yarrow 随机数生成器
    yarrow256_init(&rng, 0, NULL);
    
    // 从 /dev/urandom 获取熵数据并种下种子
    read_entropy_from_dev_urandom(&rng, RANDOM_BUFFER_SIZE);
    
    printf("开始测试 Yarrow 随机数生成器的输出...\\n");

    // 生成并打印随机数据
    for (int i = 0; i < NUM_RANDOM_CHUNKS; ++i) {
        uint8_t buffer[RANDOM_BUFFER_SIZE];
        yarrow256_random(&rng, RANDOM_BUFFER_SIZE, buffer);
        
        printf("随机数 %d: ", i + 1);
        for (size_t j = 0; j < RANDOM_BUFFER_SIZE; j++) {
            printf("%02x ", buffer[j]);
        }
        printf("\\n");
    }

    printf("测试完成。\\n");

    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test7 nettle_test7.c -lnettle')
        code, nettle_result = self.cmd("./nettle_test7")
        self.assertIn('测试完成。', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test7 nettle_test7.c')
